package controllers

import (
	"github.com/kataras/iris"
	"github.com/medivhzhan/weapp"
	"log"
	"lottery/comm"
	"lottery/conf"
	"lottery/models"
	"lottery/services"
	"lottery/web/utils"
)

type IndexController struct {
	Ctx         iris.Context
	ServiceUser services.UserService
}

// POST /
// 接口测试
func (c *IndexController) Get() string {
	c.Ctx.Header("Content-Type", "text/html")
	return "欢迎使用计算机协会抽奖系统"
}

// POST /register params: username, password, gender, avatar, niki
// 普通注册账号
func (c *IndexController) PostRegister() map[string]interface{} {

	username := c.Ctx.URLParam("username")

	if exist := c.ServiceUser.IsUserExist(username); exist {
		return map[string]interface{}{
			"code": 130,
			"msg":  "user exist",
		}
	}

	password := c.Ctx.URLParam("password")
	gender, _ := c.Ctx.URLParamInt("gender")
	avatar := c.Ctx.URLParam("avatar")
	niki := c.Ctx.URLParam("niki")

	user := models.TbUser{
		Username:   username,
		Password:   password,
		Avatar:     avatar,
		Gender:     gender,
		NikiName:   niki,
		Status:     1,
		CreateTime: comm.NowUnix(),
		UpdateTime: comm.NowUnix(),
	}

	err := c.ServiceUser.Create(&user)
	if err != nil {
		log.Println("index.PostRegister() failed, err=", err)
		return utils.RespCode(500)
	}
	return utils.RespCode(0)
}

// POST /login Params: username, password
// 普通账号登录
func (c *IndexController) PostLogin() map[string]interface{} {
	resp := make(map[string]interface{})

	username := c.Ctx.FormValue("username")
	password := c.Ctx.FormValue("password")

	has, user := c.ServiceUser.GetByUsername(username)
	if !has {
		// 用户不存在
		resp["code"] = 200
		resp["msg"] = "login failed"
		return resp
	}
	if user.Password != password {
		// 密码错误
		resp["code"] = 200
		resp["msg"] = "login failed"
		return resp
	}
	data := make(map[string]interface{})
	data["user_id"] = user.Id
	token, err := utils.GetESToken(data)
	if err != nil {
		return utils.RespCode(500)
	}

	return map[string]interface{}{
		"code":  0,
		"msg":   "success",
		"token": token,
	}
}

// POST /wxlogin params: code
// 微信小程序登录
func (c *IndexController) PostWxlogin() map[string]interface{} {

	code := c.Ctx.FormValue("code")

	log.Println("Code:", code)

	wxResp, err := weapp.Login(conf.AppID, conf.AppSecret, code)
	if err != nil {
		log.Println("index.PostWXLogin() failed, err=", err)
		return utils.RespCode(500)
	}

	// 处理微信登录失败
	if wxResp.ErrCode != 0 {
		return map[string]interface{}{
			"code": 120,
			"msg":  wxResp.ErrMSG,
		}
	}

	if has, user := c.ServiceUser.GetByOpenId(wxResp.OpenID); has {
		// 用户不存在则注册
		nikiName := c.Ctx.FormValue("niki")
		avatar := c.Ctx.FormValue("avatar")
		gender := c.Ctx.FormValue("gender")
		log.Println("niki", nikiName)
		log.Println("avatar", avatar)
		log.Println("gender", gender)

		genderInt := int(comm.GetInt64(gender, -1))

		newUser := &models.TbUser{
			Avatar:     avatar,
			Gender:     genderInt,
			NikiName:   nikiName,
			Openid:     wxResp.OpenID,
			Status:     1,
			CreateTime: comm.NowUnix(),
			UpdateTime: comm.NowUnix(),
		}
		if err := c.ServiceUser.Create(newUser); err != nil {
			log.Println("index.PostWxlogin() failed, err=", err)
			return utils.RespCode(500)
		} else {

			token, getTokenErr := utils.GetESToken(map[string]interface{}{
				"user_id": newUser.Id,
			})
			if getTokenErr != nil {
				return utils.RespCode(500)
			}

			return map[string]interface{}{
				"code":  0,
				"msg":   "login success",
				"token": token,
			}
		}

	} else {
		token, getTokenErr := utils.GetESToken(map[string]interface{}{
			"user_id": user.Id,
		})
		if getTokenErr != nil {
			return utils.RespCode(500)
		}
		return map[string]interface{}{
			"code":  0,
			"msg":   "login success",
			"token": token,
		}
	}
}

// POST /wxregnorm params: token, username, password
// 微信绑定默认账号
func (c *IndexController) PostWxregnorm() map[string]interface{} {
	token := c.Ctx.FormValue("token")

	if ret, claims, err := utils.VerifyESToken(token); err != nil {
		return utils.RespCode(500)
	} else if !ret {
		return utils.RespCode(100)
	} else {
		userId := claims.Get("user_id").(int)
		has, user := c.ServiceUser.Get(userId)
		if !has {
			return utils.RespCode(140)
		}
		username := c.Ctx.FormValue("username")
		password := c.Ctx.FormValue("password")
		user.Username = username
		user.Password = password

		if err := c.ServiceUser.Update(user, []string{"username", password}); err != nil {
			return utils.RespCode(500)
		}
		return utils.RespCode(0)
	}

}
